package com.banciyuan.bcywebview.biz.detail.comment;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.daoexample.model.DetailComment;
import de.greenrobot.daoexample.model.DetailType;

/**
 * Created by squall on 2016/1/13.
 */
public class CommentHelper {

    private Context mContext;
    private RequestQueue mQueue;
    private DetailType mDetailType;

    public CommentHelper(Context mContext, DetailType detailType) {
        this.mContext = mContext;
        this.mQueue = VolleyQueue.getRquest(mContext);
        this.mDetailType = detailType;
    }

    public void getSingleCommentData(String commentId, final IGetComment iGetComment) {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                iGetComment.getSucc(response);
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                iGetComment.getFail();
            }
        };
        getSingleCommentData(onSuccess, onError, commentId);
    }

    /**
     * 获取评论列表
     *
     * @param pageNum
     * @param iGetComment
     */
    public void getCommentData(int pageNum, final IGetComment iGetComment) {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                iGetComment.getSucc(response);
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                iGetComment.getFail();
            }
        };
        CommonApiUtils.getCommentData(mContext, mQueue, onSuccess, onError, mDetailType, pageNum);
    }

    /**
     * 获取回复列表
     *
     * @param commentId
     * @param pageNum
     * @param iGetComment
     */
    public void getReplyData(String commentId, int pageNum, final IGetComment iGetComment) {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                iGetComment.getSucc(response);
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                iGetComment.getFail();
            }
        };
        getReplyData(onSuccess, onError, commentId, pageNum);
    }

    /**
     * 删除单条评论
     *
     * @param deleteId
     * @param commentListener
     */
    public void deleteCommit(String deleteId, final IGetComment commentListener) {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, mContext)) {
                        commentListener.getSucc(response);
                    } else {
                        commentListener.getFail();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    commentListener.getFail();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                commentListener.getFail();
            }
        };
        deleteComment(onSuccess, onError, deleteId);
    }

    /**
     * 删除单条回复
     *
     * @param commentId
     * @param replyId
     * @param commentListener
     */
    public void deleteReply(String commentId, String replyId, final IGetComment commentListener) {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, mContext)) {
                        commentListener.getSucc(response);
                    } else {
                        commentListener.getFail();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    commentListener.getFail();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                commentListener.getFail();
            }
        };
        deleteReply(onSuccess, onError, commentId, replyId);
    }


    private boolean getSingleCommentData(Response.Listener<String> onSuccess, Response.ErrorListener onError, String commentId) {
        String url;
        List<BcyPair> paramsList = new ArrayList<>();
        if (mDetailType == null) return false;
        switch (mDetailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.getOneCommentData();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                paramsList.add(new BcyPair(HttpUtils.DPID, mDetailType.getDp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.getOneCommentData();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                paramsList.add(new BcyPair(HttpUtils.CPID, mDetailType.getCp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.getOneCommentData();
                paramsList.add(new BcyPair(HttpUtils.UDID, mDetailType.getUd_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                url = HttpUtils.BASE_URL + GroupApi.getOneCommentData();
                paramsList.add(new BcyPair(HttpUtils.POSTID, mDetailType.getPost_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.getOneCommentData();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                paramsList.add(new BcyPair(HttpUtils.WPID, mDetailType.getWp_id()));
                break;
            default:
                return false;
        }
        paramsList.add(new BcyPair(HttpUtils.COMMENT_ID, commentId));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(mContext).getToken()));

        Map<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
        return true;
    }

    private boolean getReplyData(Response.Listener<String> onSuccess, Response.ErrorListener onError, String commentId, int pageNum) {
        String url;
        List<BcyPair> paramsList = new ArrayList<>();
        if (mDetailType == null) return false;
        switch (mDetailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.getCommentReplyList();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.getCommentReplyList();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.getCommentReplyList();
                paramsList.add(new BcyPair(HttpUtils.UDID, mDetailType.getUd_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                url = HttpUtils.BASE_URL + GroupApi.getCommentReplyList();
                paramsList.add(new BcyPair(HttpUtils.POSTID, mDetailType.getPost_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.getCommentReplyList();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                break;
            default:
                return false;
        }
        paramsList.add(new BcyPair(HttpUtils.COMMENT_ID, commentId));
        paramsList.add(new BcyPair(HttpUtils.PAGE, String.valueOf(pageNum)));
        paramsList.add(new BcyPair(HttpUtils.LIMIT, "10"));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(mContext).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
        return true;
    }

    private Boolean deleteComment(Response.Listener<String> onSuccess, Response.ErrorListener onError, String deleteId) {
        String url;
        switch (mDetailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.getDelreply();
                break;
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.getDelreply();
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.getDelreply();
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                url = HttpUtils.BASE_URL + GroupApi.getDelreply();
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.getDelreply();
                break;
            default:
                return false;
        }
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.ID, deleteId));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(mContext).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
        return true;
    }

    private Boolean deleteReply(Response.Listener<String> onSuccess, Response.ErrorListener onError, String commentId, String replyId) {
        String url;
        List<BcyPair> paramsList = new ArrayList<>();
        switch (mDetailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.deleteReplyComment();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.deleteReplyComment();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.deleteReplyComment();
                paramsList.add(new BcyPair(HttpUtils.UDID, mDetailType.getUd_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                url = HttpUtils.BASE_URL + GroupApi.deleteReplyComment();
                paramsList.add(new BcyPair(HttpUtils.POSTID, mDetailType.getPost_id()));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.deleteReplyComment();
                paramsList.add(new BcyPair(HttpUtils.RPID, mDetailType.getRp_id()));
                break;
            default:
                return false;
        }
        paramsList.add(new BcyPair(HttpUtils.COMMENT_ID, commentId));
        paramsList.add(new BcyPair(HttpUtils.REPLY_ID, replyId));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(mContext).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);

        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
        return true;
    }

    public static void processTemList(List<DetailComment> tempList) {
        for (int i = 0; i < tempList.size(); i++) {
            DetailComment data = tempList.get(i);
            processDetailComment(data);
            if (null != data.getComments()) {
                for (int j = 0; j < data.getComments().size(); j++) {
                    processTemList(data.getComments());
                }
            }
        }
    }

    public static void processDetailComment(DetailComment data) {
        String content = data.getContent();
        if (content.contains("[reply]")) {
            data.setType(2);
            Pattern p = Pattern.compile("\\[reply\\](.*?:)");
            Matcher m = p.matcher(data.getContent());
            while (m.find()) {
                data.setReplyCotent(m.group(1));
                continue;
            }
            content = content.replaceAll("\\[reply\\](.*?)((\\[/reply\\])+?)", " ");
            data.setContent(content);
        } else {
            data.setType(1);
            Pattern p = Pattern.compile("回复 @(.*?):");
            Matcher m = p.matcher(data.getContent());
            while (m.find()) {
                data.setReplyCotent(content.replaceAll(Pattern.quote(m.group(0)), ""));
                setReplyedName(data, m.group(1));
                continue;
            }
        }
    }

    private static void setReplyedName(DetailComment data, String tempContent) {
        data.setReplyedName(tempContent.trim());
    }

    public static void processTalkList(List<DetailComment> tempList) {
        String content;
        if (null == tempList)
            return;
        for (int i = 0; i < tempList.size(); i++) {
            content = tempList.get(i).getContent();
            DetailComment data = tempList.get(i);
            if (content.contains("[reply]")) {
                data.setType(2);
                Pattern p = Pattern.compile("\\[reply\\].*?@(.*?):");
                Matcher m = p.matcher(data.getContent());
                while (m.find()) {
                    data.setReplyCotent("<font color='#4d70a5'>" + m.group(1) + "</font>：");
                    continue;
                }
                content = content.replaceAll("\\[reply\\](.*?)((\\[/reply\\])+?)", " ");
                data.setContent(content);
            } else {
                data.setType(1);
                data.setContent(content);
            }
        }
    }

}
